<?php
/**
 * Created by PhpStorm.
 * User: idcu
 * Date: 2016/3/12
 * Time: 13:48
 */
namespace Service\Model;
use IDCU\Model\RelationModel;

class WxOrderModel extends RelationModel
{
    protected $connection = array(
        'db_type'       =>  'mysql',
        'db_host'       =>  '114.55.30.131',
        'db_port'       =>  '3306',
        'db_name'       =>  'wxsmart',
        'db_user'       =>  'zhkj_crm',
        'db_pwd'        =>  'AdkdCGP7fHcjht5c',
        'db_charset'    =>  'utf8',
        'db_debug'      =>  true,
    );
    protected $tablePrefix = '';
    protected $tableName = 'tp_qtservice';

    protected $_link = array(
        'OrderStep' => array(
            'mapping_type' => self::HAS_MANY,
            'mapping_name' => 'step',
            'foreign_key'  => 'sid'
        )
    );

    public function roll($id=0, $step=false){
        $data = $this->selectStep(false,$step,9999,$id)['data'];
//        $where['wecha_id'] = '';
//        $data = $this->where($where)->data(['phone_order'=>1])->save();
        return $data;
    }

    public function edit(){
        $data = $this->create();
        $parent = I('parent');
        $type_id = I('type_id');

        $data['type'] = ($parent==242?1:2);
        $data['entry_id'] = $type_id;
        $data['entry_name'] = M('RepairType')->find($type_id)['name'];
        $ok = $this->data($data)->save();
        if($ok){
            $res['status'] = 1;
            $res['msg'] = '修改成功';
        }else{
            $res['status'] = false;
            $res['msg'] = '修改失败';
        }
        return $res;
    }
    
    public function selectStep($type=false, $step=false, $pageSize=20, $id=false, $wecha_id=false, $handler=false, $info=false){
        //时间搜索
        $start_time = I('start_time');
        $end_time = I('end_time');
        $community_id = I('community_id');
        $phone_order = I('phone_order');
        if ($start_time)
            $start_time = strtotime($start_time);
        if ($end_time)
            $end_time = strtotime($end_time);
        if ($start_time && !$end_time)
            $where['createtime'] = array('egt',$start_time);
        elseif (!$start_time && $end_time)
            $where['createtime'] = array('elt',$end_time);
        elseif ($start_time && $end_time)
            $where['createtime'] = array('BETWEEN',"$start_time,$end_time");
        //搜索weicha_id
        if($wecha_id)
            $where['wecha_id'] = $wecha_id;
        if($community_id)
            $where['community_id'] = $community_id;
        //搜索处理过的订单
        if($handler){
            $me = $this->sessionEmployee();
            $orderId = $this->getHandler($me['id']);
            if($orderId)
                $where['id'] = array('in', $orderId);
        }
        if($phone_order)
            $where['phone_order'] = 1;
        else
            $where['phone_order'] = 0;
        //搜索关键词
        $key = I('key');
        $selectType = I('selectType');
        if($key == 'undefined')
            $key = false;
        $key = trim(rtrim($key));
        if($selectType==1 && $key){
            //事件
            $where['info'] = array('like', "%$key%");
        }elseif ($selectType==2 && $key){
            //保报修人
            if(preg_match("/^\d+$/", $key)) {
                $userData = D('Admin/WxuserInfo')->where(['tel'=>['like',"%$key%"]])->select();
            } else {
                $userData = D('Admin/WxuserInfo')->where(['realname'=>['like',"%$key%"]])->select();
            }
            foreach ($userData as $v){
                $userId[] = $v['wecha_id'];
            }
            $map['wecha_id'] = array('in', implode(',',$userId));
            $map['info'] = array('like', "%$key%");
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }elseif ($selectType==3 && $key){
            //地址
            $where['address'] = array('like', "%$key%");
        }elseif ($selectType==4 && $key){
            //维修师傅
            if(preg_match("/^\d+$/", $key)) {
                $userData = D('Admin/Employee')->where(['mobile'=>['like',"%$key%"]])->select();
            } else {
                $userData = D('Admin/Employee')->where(['name'=>['like',"%$key%"]])->select();
            }
            foreach ($userData as $v){
                $userId[] = $v['id'];
            }
            $where['handler_man'] = array('in', $userId);
        }elseif ($selectType==5 && $key){
            //客服
            if(preg_match("/^\d+$/", $key)) {
                $userData = M('User')->where(['mobile'=>['like',"%$key%"]])->select();
            } else {
                $userData = M('User')->where(['real_name'=>['like',"%$key%"]])->select();
            }
            foreach ($userData as $v){
                $userId[] = $v['id'];
            }
            $where['service_id'] = array('in', $userId);
        } elseif ($selectType==6 && $key){
            $where['serialno'] = array('like', "%$key%");
        }

        if($type!==false)
            $where['type']= array('eq', $type);
        if($info)
            $where['info']= array('like', "%$info%");
        if($step==1){
            $hour = C('ROB_TIME');
            $searchTime = time()-$hour;
            $where['step']= array('in', '1,2');
            $where['rob_start_time'] = array('elt',$searchTime);
        }elseif($step==2){
            $hour = C('ROB_TIME');
            $searchTime = time()-$hour;
            $where['step']= array('eq', 2);
            $where['rob_start_time'] = array('gt',$searchTime);
        }elseif($step!=false)
            $where['step']= array('in', $step);
        if($id || $id=I('id'))
            $where['id']= array('gt', $id);
        else
            $where['id']= array('gt', 2139);

        if(chckRole(4)){
            $nowUser = M('User')->find(session('authId'));
            $dept_name = $nowUser['DEPT_NAME'];
            $nowCommunity_id = M('Community')->where(['name'=>['like',"%$dept_name%"]])->find()['id'];
            if($nowUser['assistant_map'])
                $map['community_id'] = array('in',$nowUser['assistant_map']);
            else
                $map['community_id'] = array('eq',$nowCommunity_id);
            $map['_logic'] = 'or';
            $where['_complex'] = $map;
        }
        $where['delete_status'] = 1;
//        dd($where);
        /************************************* 翻页 ****************************************/
        $count = $this->where($where)->count();
        $page = new \ZL\Page($count, $pageSize);
        $data['page'] = $page->show();
        /************************************** 取数据 ******************************************/
        $orderData = $this->where($where)->order('createtime desc')->limit($page->limit.','.$page->listRows)->select();
//        myDump($this->getLastSql());
//        myDump($orderData);die;
        $data['data'] = $this->strChange($orderData);
        return $data;
    }

    public function countStep($step=false,$id=2139){
        if($step==1){
            $hour = C('ROB_TIME');
            $searchTime = time()-$hour;
            $where['step']= array('in', '1,2');
            $where['rob_start_time'] = array('elt',$searchTime);
        }elseif($step==2){
            $hour = C('ROB_TIME');
            $searchTime = time()-$hour;
            $where['step']= array('eq', 2);
            $where['rob_start_time'] = array('gt',$searchTime);
        }elseif($step!=false)
            $where['step']= array('in', $step);
        if($id!=false || $id=I('id'))
            $where['id']= array('gt', $id);
//        myDump($where);die;
        $count = $this->where($where)->count();
        return $count;
    }

    public function strChange($orderData=false){
        foreach ($orderData as &$v) {
            switch ($v['step']){
                case 1:
                    $v['step_title'] = '未受理';
                    $v['is_edit'] = 1;
                    break;
                case 2:
                    $hour = C('ROB_TIME');
                    $searchTime = time()-$hour;
                    if($v['rob_start_time'] < $searchTime) {
                        $v['step_title'] = '无人抢单';
                        $v['is_edit'] = 1;
                    }
                    else {
                        $v['step_title'] = '抢单中';
                        $v['is_edit'] = -1;
                    }
                    break;
                case 3:
                    $v['step_title'] = '价格确认中';
                    $v['is_edit'] = -1;
                    break;
                case 4:
                    if($v['repair_start_time'])
                        $v['step_title'] = '开始维修';
                    else
                        $v['step_title'] = '价格确认完毕';
                    $v['is_edit'] = -1;
                    break;
                case 5:
                    $v['step_title'] = '完成维修';
                    $v['is_edit'] = -1;
                    break;
                case 6:
                    $v['step_title'] = '订单完成';
                    $v['is_edit'] = -1;
                    break;
                case 7;
                    $v['step_title'] = '已评价';
                    $v['is_edit'] = -1;
                    break;
                case -2;
                    $v['step_title'] = '已取消';
                    $v['is_edit'] = -1;
                    break;
                case -8;
                    $v['step_title'] = '等待审核';
                    $v['is_edit'] = -1;
                    break;
            }
            $v['type_name'] = $v['type']==2?'公共维修':'家庭维修';
            $handler = D('Admin/Employee')->find($v['handler_man']);
            $v['handler_name'] = $handler['name'];
            $v['handler_mobile'] = $handler['mobile'];

                $v['customer'] = $this->getUserInfo($v['wecha_id']);
            $v['community_name'] = M('Community')->find($v['community_id'])['name'];
            if($v['service_id'])
                $v['service_name'] = M('User')->find($v['service_id'])['real_name'];
            if(D('Admin/Employee')->where(['name'=>$v['customer']['realname']])->find())
                $v['is_repair'] = 1;
            $depart = D('Admin/Depart')->where(['community_id'=>$v['community_id']])->find()['id'];
            $v['depart'] = $depart;
            $has_repair = D('Admin/Employee')->where(['department'=>['like',"%$depart%"]])->find()['id'];
            $v['has_repair'] = $has_repair;
            if($v['rob_start_time'])
                $v['rob_start_date'] = date("Y-m-d H:i:s",$v['rob_start_time']);

            switch ($v['evaluate']) {
                case 1:
                    $v['assess'] = '非常不满意';
                    break;
                case 2:
                    $v['assess'] = '不满意';
                    break;
                case 3:
                    $v['assess'] = '一般';
                    break;
                case 4:
                    $v['assess'] = '满意';
                    break;
                case 5:
                    $v['assess'] = '非常满意';
                    break;
                default:
                    $v['assess'] = '未评价';
                    break;
            }

            if($v['customer']['id']==9188){
                preg_match('/(1[3|4|5|7|8]\d{9})/', $v['info'],$matches);
                $v['customer']['tel'] = $matches[0];
                preg_match("/[\x80-\xff]+/", $v['info'],$names);
                preg_match("/[\x{4e00}-\x{9fa5}]+/u", $v['info'],$names);
//                myDump($names);die;
                $v['customer']['real_name'] = str_replace($names[0].':','',$v['info']);
                preg_match("/^[\x{4e00}-\x{9fa5}]+/u", $v['customer']['real_name'],$other);
                $v['customer']['realname'] = $other[0];
//                myDump($other);
//                myDump($v['customer']['realname']);die;
            }
        }
//        dd($orderData);
        return $orderData;
    }

    public function adding(){
        $name = I('name');
        $parent = I('parent');
        if($parent==291){
            $res = D('Order')->adding();
            return $res;
        }
        $tel = I('tel');
        $type_id = I('type_id');
        $info = I('info');
        $tel = preg_replace('/(0*)(1[^0])(\d{9})/','$2$3',$tel);
        $addressData = explode(',',I('address'));
        $address = $addressData[0];
        $community_id = $addressData[1];
        $where['realname'] = $name;
        $where['tel'] = $tel;
        $userinfo = D('Admin/WxuserInfo')->where($where)->find();

        if($userinfo) {
            $data['wecha_id'] = $userinfo['wecha_id'];
            $data['token'] = $userinfo['token'];

            $data['info'] = $info;
        }else{

            $data['info'] = '联系方式:'.$name.$tel.'   '.$info;
        }
        $data['serialno'] = $this->snGenerate($community_id);
        $data['type'] = ($parent==242?1:2);
        $data['community_id'] = $community_id;
        $data['entry_id'] = $type_id;
        $data['entry_name'] = M('RepairType')->find($type_id)['name'];
        $data['address'] = $address;
        $data['step'] = 1;
        $data['phone_order'] = 1;
        $data['createtime'] = time();
//        myDump($add_id);
//        myDump($data);
        $add_id = $this->add($data);
        repairSend($add_id);
        if($add_id){
            $employee = $this->sessionEmployee();
            if(!$employee)
                $employeeId = 0;
            else
                $employeeId = $employee['id'];
            $_data = array(
                'sid' => $add_id,
                'title' => '业主报修',
                'step' => 1,
                'class' => 'info',
                'data' => '',
                'userid' => $employeeId,
                'createtime' => time(),
            );
            $ok = D('OrderStep')->add($_data);
//            myDump($ok);die;
            if($ok)
                return true;
            else
                return false;
        }else
            return false;
    }

    public function rob($id){
        $data['id'] = $id;
        $data['step'] = 2;
        $data['rob'] = 1;
        $data['rob_start_time'] = time();
        $data['service_id'] = session('authId');
        if($this->data($data)->save()){
            $employee = $this->sessionEmployee();
            if(!$employee)
                $employeeId = 0;
            else
                $employeeId = $employee['id'];
            $_data = array(
                'sid' => $id,
                'title' => '设为自助抢单',
                'step' => 2,
                'class' => 'info',
                'data' => '',
                'userid' => $employeeId,
                'createtime' => time(),
            );
            $ok = D('OrderStep')->add($_data);
            repairSend($id);
            if($ok)
                return true;
            else
                return false;
        }
        return false;
    }
    public function delete($id){
        $data['id'] = $id;
        $data['delete_status'] = -1;
        if($this->data($data)->save()){
            $employee = $this->sessionEmployee();
            if(!$employee)
                $employeeId = 0;
            else
                $employeeId = $employee['id'];
            $_data = array(
                'sid' => $id,
                'title' => '删除字段',
                'step' => -4,
                'class' => 'info',
                'data' => '',
                'userid' => $employeeId,
                'createtime' => time(),
            );
            $ok = D('OrderStep')->add($_data);
            if($ok)
                return true;
            else
                return false;
        }
        return false;
    }

    public function off($oid,$remark){
//        myDump($remark);die;
        $data['id'] = $oid;
        $data['step'] = -2;
        $data['service_id'] = session('authId');
        $ok = D('WxOrder')->data($data)->save();
        if($ok){
            repairSend($oid);
            $employee = $this->sessionEmployee();
            if(!$employee)
                $employeeId = 0;
            else
                $employeeId = $employee['id'];

            $jsremark = array('remark'=>$remark);
            $jsremark = json_encode($jsremark, JSON_UNESCAPED_UNICODE);
            $_data = array(
                'sid' => $oid,
                'title' => '取消订单',
                'step' => -2,
                'class' => 'info',
                'data' => $jsremark,
                'userid' => $employeeId,
                'createtime' => time(),
            );
            $ok = D('OrderStep')->add($_data);
            if($ok)
                return true;
            else
                return false;
        }else
            return false;
    }

    public function appoint($oid, $mid){
        $this->autoEval();
        $data['id'] = $oid;
        $data['handler_man'] = $mid;
        $data['step'] = 3;
        $data['service_id'] = session('authId');
        $ok = $this->data($data)->save();
        if($ok){
            repairSend($oid);
            $employee = $this->sessionEmployee();
            if(!$employee)
                $employeeId = 0;
            else
                $employeeId = $employee['id'];
            $remark = array('指派给'=>$mid);
            $remark = json_encode($remark, JSON_UNESCAPED_UNICODE);
            $_data = array(
                'sid' => $oid,
                'title' => '人工指派',
                'step' => 3,
                'class' => 'info',
                'data' => $remark,
                'userid' => $employeeId,
                'createtime' => time(),
            );
            $ok = D('OrderStep')->add($_data);
            if($ok)
                return true;
            else
                return false;
        }else
            return false;
    }

    public function order_confirm($id,$step){
        $where['id'] = $id;
        $where['step'] = $step;
        $data = $this->where($where)->find();
        if($data)
            return true;
        return false;
    }

    public function repairManList($orderId){
        $cid = $this->find($orderId)['community_id'];
//        var_dump($cid);
        $name = M('Community')->find($cid)['name'];
//        var_dump($name);
        $depId = D('Admin/Depart')->where(array('name'=>array('eq',$name)))->find()['id'];
//        var_dump($depId);die;
        $people = D('Admin/Depart')->getRepair($depId);
        foreach ($people as &$one) {
            $id = $one['id'];
            $one['count'] = $this->orderCount($id);
//            D('Admin/WxuserInfo')
        }
        return $people;
    }

    public function getInfo($id){
        $data = $this->find($id);
        $data['type_name'] = $data['type']==2?'公共维修':'家庭维修';
        $data['pid'] = D('RepairType')->find($data['entry_id'])['pid'];
        switch ($data['step']){
            case 1:
                $data['step_title'] = '未受理';
                $data['is_edit'] = 1;
                break;
            case 2:
                $hour = C('ROB_TIME');
                $searchTime = time()-$hour;
                if($data['rob_start_time'] < $searchTime) {
                    $data['step_title'] = '无人抢单';
                    $data['is_edit'] = 1;
                }
                else {
                    $data['step_title'] = '抢单中';
                    $data['is_edit'] = -1;
                }
                break;
            case 3:
                $data['step_title'] = '价格确认中';
                $data['is_edit'] = -1;
                break;
            case 4:
                if($data['repair_start_time'])
                    $data['step_title'] = '开始维修';
                else
                    $data['step_title'] = '价格确认完毕';
                $data['is_edit'] = -1;
                break;
            case 5:
                $data['step_title'] = '完成维修';
                $data['is_edit'] = -1;
                break;
            case 6:
                $data['step_title'] = '订单完成';
                $data['is_edit'] = -1;
                break;
            case 7;
                $data['step_title'] = '已评价';
                $data['is_edit'] = -1;
                break;
            case -2;
                $data['step_title'] = '已取消';
                $data['is_edit'] = -1;
                break;
            case -8;
                $data['step_title'] = '等待审核';
                $data['is_edit'] = -1;
                break;
        }
        $handler = D('Admin/Employee')->find($data['handler_man']);
        $data['handler_name'] = $handler['name'];
        $data['handler_mobile'] = $handler['mobile'];

        $data['customer'] = $this->getUserInfo($data['wecha_id']);
        $data['pic'] = M('QtserviceImg','tp_','DB_WX')->where(array('sid'=>$data['id']))->select();
        $info = D('Service/OrderStep')->where(array('sid'=>$data['id']))->order('createtime asc')->select();
        $data['community_name'] = M('Community')->find($data['community_id'])['name'];
        if($data['service_id'])
            $data['service_name'] = M('User')->find($data['service_id'])['real_name'];
        if($data['createtime'])
            $data['create_time'] = date('Y-m-d H:i:s',$data['createtime']);
        if($data['rob_start_time'])
            $data['rob_start_date'] = date('Y-m-d H:i:s',$data['rob_start_time']);
        foreach ($info as $k=>$v) {
            $data['list'][$k]['time'] = date('Y-m-d H:i:s',$v['createtime']);
            $data['list'][$k]['title'] = $v['title'];
//            $data['list'][$k]['people'] = D('Admin/Employee')->find($v['userid'])['name'];;
////            myDump(unserialize($v['data']));
//            $v['data'] = str_replace('money','"金额"',$v['data']);
//            $v['data'] = str_replace('remark','"说明"',$v['data']);
            $list = json_decode($v['data'],true);
            if($v['data']) {
//                myDump($v['data']);
//                myDump($list);
                foreach ($list as $kk => &$vv) {
                    if($v['step']==3)
                        $vv = D('Admin/Employee')->find($vv)['name'];
                    if ($data['list'][$k]['data'])
                        $data['list'][$k]['data'] .= ', ';
                    $data['list'][$k]['data'] .= $kk . '=' . $vv;
                }
            }
        }

            switch ($data['evaluate']){
                case 1:
                    $data['assess'] = '非常不满意';
                    break;
                case 2:
                    $data['assess'] = '不满意';
                    break;
                case 3:
                    $data['assess'] = '一般';
                    break;
                case 4:
                    $data['assess'] = '满意';
                    break;
                case 5:
                    $data['assess'] = '非常满意';
                    break;
                default:
                    $data['assess'] = '未评价';
                    break;
            }
//        dd($data);
        return $data;
    }

    public function orderCount($id,$oid=false){
        $where['handler_man'] = $id;
        $where['step'] = array('in', '5,6,7');
        $data['history'] = $this->where($where)->count();
        $where['step'] = array('in', '3,4');
        if($oid)
        $where['id'] = array('gt', $oid);
        $data['now'] = $this->where($where)->count();
        return $data;
    }

    public function snGenerate($community_id){
        $community = M('Community')->find($community_id);
        $crmId = $community['no'];

        $sn = date("ymd") .$crmId ."01" . rand(1000, 9999);
        return $sn;
    }
    
    protected function _after_select(&$result, $options)
    {
        parent::_after_select($result, $options); // TODO: Change the autogenerated stub
        foreach($result as $k=>&$v){
            if($v['createtime'])
                $result[$k]['create_time'] = date('Y-m-d H:i:s',$v['createtime']);

            if($v['rob_start_time'])
                $v['rob_start_date'] = date("Y-m-d H:i:s",$v['rob_start_time']);
        }
    }

    protected function getUserInfo($wecha=false, $name=false){
        $qtcModel = D('Admin/WxuserInfo');
        if($wecha)
            $where['wecha_id'] = $wecha;
        if($name)
            $where['realname'] = array('like', "%$name%");
        $qtCustomer = $qtcModel->where($where)->find();
        return $qtCustomer;
//        $data = $qtcModel->select();
//        echo '<pre>';
//        var_dump($data);die;
    }
    protected function sessionEmployee($id=false){
        if(!$id)
            $id = session('authId');
        $real_name = M('User')->find($id)['real_name'];
        $data = D('Admin/Employee')->where(array('name'=>$real_name))->find();
        return $data;
    }
    protected function getHandler($id){
        $data = D('Service/OrderStep')->where(array('userid'=>$id))->order('createtime asc')->select();
        foreach ($data as $v){
            $order [$v['sid']] = 1;
        }
        $orderId = '';
        foreach ($order as $k=>$v) {
            if($orderId)
                $orderId .= ','.$k;
            else
                $orderId .= $k;
        }
        return $orderId;
    }

    public function done(){
        $id = I('id');
        $orderData = $this->getInfo($id);
        $data['id'] = $id;
        $data['step'] = 6;
        $done_id = D('Admin/Employee')->where(['name'=>$orderData['customer']['realname']])->find()['id'];
        $data['handler_man'] = $done_id;
        $data['service_id'] = session('authId');
        $ok = $this->data($data)->save();
        if($ok){
            repairSend($id);
            $employee = $this->sessionEmployee();
            if(!$employee)
                $employeeId = 0;
            else
                $employeeId = $employee['id'];
            $_data = array(
                'sid' => $id,
                'title' => '直接完成',
                'step' => 6,
                'class' => 'info',
                'data' => '',
                'userid' => $employeeId,
                'createtime' => time(),
            );
            $ok = D('OrderStep')->add($_data);
            if($ok)
                return true;
            else
                return false;
        }else
            return false;
    }
    public function autoEval(){
        $where['a.evaluate'] = 0;
        $where['a.step'] = 6;
        $time = time()-3600*24*3;
        $where['b.createtime'] = array('lt',$time);
        $where['b.step'] = 6;
        $data = $this->alias('a')->field('a.id,a.step')->join('left join tp_qtservice_step b on a.id=b.sid')->where($where)->select();
//        myDump(count($data));
//        myDump($data);die;
        foreach ($data as $k=>$v) {
            $v['evaluate'] = 5;
            $this->data($v)->save();
            $_data = array(
                'sid' => $v['id'],
                'title' => '自动评价',
                'step' => 7,
                'class' => 'info',
                'data' => '',
                'userid' => '',
                'createtime' => time(),
            );
            D('OrderStep')->add($_data);
        }
    }
}